package br.edu.fasete.javaroad.base;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.io.*;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import br.edu.fasete.javaroad.log.LogManager;

public class CodeGenerator {

	static {
		try {
			Properties p = new Properties();

			p.setProperty(Velocity.RESOURCE_LOADER, "classpath");
			p.setProperty(
					"classpath." + Velocity.RESOURCE_LOADER + ".class",
			"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");

			p.setProperty(
					"classpath." + Velocity.RESOURCE_LOADER + ".cache", "false");

			p.setProperty(
					"classpath." + Velocity.RESOURCE_LOADER + ".modificationCheckInterval", "2");
			Velocity.init(p);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void aplicarStringTemplate(String template, String arquivo, HashMap<String, Object> variaveis) {
		try {

			VelocityContext context = new VelocityContext();

			Set<String> nomes = variaveis.keySet();
			Iterator<String> it = nomes.iterator();
			while(it.hasNext()) {
				String var = it.next();
				context.put(var, variaveis.get(var));	
			}

			FileWriter arq = new FileWriter(arquivo);
			BufferedWriter writer = new BufferedWriter(arq);
			Velocity.evaluate( context, writer, "mystring", template );
			writer.flush();
			writer.close();
			arq.close();


		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void criarDiretorio(String diretorio) {
		try{	
			File fp = new File(diretorio);
			if(!fp.exists()) {
				boolean sucesso = fp.mkdirs();
				if(sucesso) {
					LogManager.getLogger().appendMessage("--->Directory " + diretorio + " build");
				} else {
					LogManager.getLogger().appendMessage("--->Could not create the directory " + diretorio);
					System.exit(0);
				}
			}
		}catch (Exception e){
			System.err.println("Error: " + e.getMessage());
		}		
	}

}